from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
import json, datetime
from django.contrib.auth import get_user_model

from apps.account.serializers import UserSerializer

User = get_user_model()

userList = []


class ChatConsumer(WebsocketConsumer):
    def connect(self):
        # print('sssssssssss', self.scope['user'])
        self.room_name = 'chatRoom'  # 聊天室
        self.room_group_name = 'dweb'
        # 异步
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )
        self.accept()

    def disconnect(self, close_code):
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name,
            self.channel_name
        )

    def receive(self, text_data=None, bytes_data=None):
        global userList
        text_data_json = json.loads(text_data)
        # {'code': '100', 'user_id': '10', 'content': 'asdasdas'}
        user = User.objects.filter(id=text_data_json['user_id']).first()
        user_info = UserSerializer(user).data
        message = {
            'userInfo': user_info,
            'create_time': datetime.datetime.now().strftime("%Y-%m-%d %H:%I:%S")
        }
        if text_data_json['code'] == '101':
            # 进入房间
            message['content'] = user.nickname + '进入房间'
            message['code'] = 101

            if user_info not in userList:
                userList.append(user_info)
        if text_data_json['code'] == '100':
            # 发送信息
            message['content'] = text_data_json['content']
            message['code'] = 100
        if text_data_json['code'] == '888':
            # 离开房间
            print('-----离开房间----------')
            if user_info in userList:
                userList.remove(user_info)
            message['content'] = user.nickname + '离开房间'
            message['code'] = 888

        event = {
            'type': 'chat_message',
            'message': message
        }
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            event
        )

    def chat_message(self, event):
        message = event['message']
        self.send(text_data=json.dumps(message))
